<?php


namespace app\admin\controller\fastflow\bill;

use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\admin\model\fastflow\CancheckIndex;
use app\admin\model\fastflow\flow\EbillCopy;
use app\admin\model\fastflow\ParticipantIndex;
use app\admin\model\fastflow\Signature;
use app\common\controller\Backend;
use fastflow\api;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;


class Common extends Backend
{
    protected $noNeedRight = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->view->assign('initiator_id', \think\Session::get()['admin']['id']);
    }

    /*
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $bill_ids = $this->filtrateBillIds();
        if (is_array($bill_ids) && empty($bill_ids)) {
            return ['total' => 0, 'rows' => []];
        }
        if (is_array($bill_ids) && !empty($bill_ids)) {
            $this->model->where('id in (' . implode(',', $bill_ids) . ')');
        }

        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        $list = $this->getSignatureInfo($list);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        //删除权限:1=本人未发起审批的,2=本人未发起审批的、流程中的,3=不允许
        $api = new api();
        $bill = Config::get('database')['prefix'] . $this->model->getName();
        $groupAccess = AuthGroupAccess::where('uid', Session::get()['admin']['id'])->find();
        $groupId = $groupAccess['group_id'];
        $group = AuthGroup::find($groupId);
        foreach (explode(',', $ids) as $id) {
            $billRow = $api->getBillRow($bill, $id);
            if ($billRow) {
                if ($group['pid'] != 0) {
                    if ($billRow['initiator_id'] != Session::get()['admin']['id']) {
                        return ['code' => 0, 'msg' => '您没有权限删除该单据'];
                    }
                    $delete_rule = 1;
                    $auth_row = (new \app\admin\model\fastflow\flow\BillAuth())->where(['bill' => $bill])->find();
                    $process = $api->getProcessByBill($bill, $billRow['id']);
                    if ($auth_row) {
                        $rules = json_decode($auth_row['rules'], true);
                        if (isset($rules['delete'])) {
                            $delete_rule = $rules['delete'];
                        }
                    }
                    if ($delete_rule == 1) {
                        if ($process) {
                            return ['code' => 0, 'msg' => '您没有权限删除该单据'];
                        }
                    }
                    if ($delete_rule == 2) {
                        if ($process) {
                            if ($process['status'] != 1) {
                                return ['code' => 0, 'msg' => '您没有权限删除该单据'];
                            }
                        }
                    }
                    if ($delete_rule == 3) {
                        return ['code' => 0, 'msg' => '您没有权限删除该单据'];
                    }
                }

                if ($billRow['initiator_id'] != Session::get()['admin']['id'] && $group['pid'] != 0) {
                    return ['code' => 0, 'msg' => '您没有权限删除该单据'];
                }
            }
        }
        $api->delBill($bill, explode(',', $ids));
        parent::del($ids);
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $can_edit_fields = [];
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $api = new api();
        $isSuperManager = false;
        $admin_id = Session::get()['admin']['id'];
        $groupAccess = AuthGroupAccess::where('uid', $admin_id)->select();
        foreach ($groupAccess as $access) {
            $groupId = $access['group_id'];
            $group = AuthGroup::find($groupId);
            if ($group['pid'] == 0) {
                $isSuperManager = true;
            }
        }
        $bill = Config::get('database')['prefix'] . $this->model->getName();
        if (input('threadid') == null) {
            if (!$isSuperManager) {
                $bill_process = $api->getProcessByBill($bill, $row['id']);
                if ($bill_process) {
                    if (input('way') == 'detail') {
                        $can_edit_fields = [];
                    } else {
                        $this->error('流程审批中，您不能直接编辑该单据', '');
                    }
                } else {
                    $agency_info = $api->checkAgency($bill, $row['id'], 1, [$row['initiator_id']]);
                    if ($agency_info) {
                        if (!in_array($admin_id, $agency_info['agency_workers']) && !$isSuperManager) {
                            $this->error('您不是超级管理员或代理人，无权限编辑该单据', '');
                        } else {
                            $can_edit_fields = true;
                        }
                    } else {
                        if ($row['initiator_id'] != Session::get()['admin']['id'] && !$isSuperManager) {
                            $this->error('您不是超级管理员或流程发起人，暂无权限编辑该单据', '');
                        } else {
                            $can_edit_fields = true;
                        }
                    }
                }
            } else {
                $can_edit_fields = true;
            }
        } else {
            $can_edit_fields = (new api())->getCanEditFields($bill, $row['id'], input('threadid'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $result = $row->allowField($can_edit_fields === true ? true : implode(',', $can_edit_fields))->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            //4.4.1--
            $this->success();
            //$this->error(__('Parameter %s can not be empty', ''));
            //--
        }

        $bill_fileds = $api->getFieldsWithComment($bill);
        $fields = [];
        foreach ($bill_fileds as $bill_filed) {
            $fields[] = $bill_filed['field'];
        }
        if ($can_edit_fields === true) {
            $can_edit_fields = $fields;
        }

        $this->assignconfig(['billFileds' => $fields, 'canEditFields' => $can_edit_fields]);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    //获取能查看的单据ids
    protected function filtrateBillIds()
    {
        //查看权限:1=所有的,2=本人发起的、当前需审批的，3=本人发起的、当前需审批的、参与过审批的
        $isSuperManager = $this->auth->isSuperAdmin();

        $bill = \think\Config::get('database')['prefix'] . $this->model->getName();
        $view_rule = 1;
        $auth_row = (new \app\admin\model\fastflow\flow\BillAuth())->where(['bill' => $bill])->find();
        if ($auth_row) {
            $rules = json_decode($auth_row['rules'], true);
            if (isset($rules['view'])) {
                $view_rule = $rules['view'];
            }
        }

        $canCheck_ids = [];
        $needStart_ids = [];
        $mine_ids = [];
        $participant_ids = [];

        $canView_ids = [];
        //$canCheck_ids
        $user_id = $this->auth->getUserInfo()['id'];
        $canCheckIndexRows_byUser = CancheckIndex::where(['bill' => $bill, 'worker_id' => $user_id])->where('scope', 'in', [1, 3])->select();//通过user_id获取待审批单据ids
        foreach ($canCheckIndexRows_byUser as $canCheckIndexRow_byUesr) {
            $canCheck_ids[] = $canCheckIndexRow_byUesr['bill_id'];
        }
        $group_ids = $this->auth->getGroupIds();
        $canCheckIndexRows_byGroup = CancheckIndex::where(['bill' => $bill])->where('scope', 'in', [2, 4])->where('worker_id', 'in', $group_ids)->select();//通过group_id获取待审批单据ids
        foreach ($canCheckIndexRows_byGroup as $canCheckIndexRow_byGroup) {
            $canCheck_ids[] = $canCheckIndexRow_byGroup['bill_id'];
        }
        $canCheck_ids = array_unique($canCheck_ids);
        //$needStart_ids
        $needStartBill_rows = $this->model->where(['initiator_id' => $user_id, 'status' => 0])->field('id')->select();//待发起单据
        foreach ($needStartBill_rows as $needStartBill_row) {
            $needStart_ids[] = $needStartBill_row['id'];
        }
        //$mine_ids
        $mineBill_rows = $this->model->where(['initiator_id' => $user_id])->field('id')->select();
        foreach ($mineBill_rows as $mineBill_row) {
            $mine_ids[] = $mineBill_row['id'];
        }

        //$participant_ids
        $participantIndex_rows = ParticipantIndex::where(['bill' => $bill, 'worker_id' => $user_id])->select();
        foreach ($participantIndex_rows as $participantIndex_row) {
            $participant_ids[] = $participantIndex_row['bill_id'];
        }

        $show_action = $this->request->request('show');
        if ($show_action == 'cancheck') {
            //需包含待发起的单据
            $canView_ids = array_merge($canCheck_ids, $needStart_ids);
        } elseif ($show_action == 'mine') {
            $canView_ids = $mine_ids;
        } elseif ($show_action == 'participant') {
            $canView_ids = $participant_ids;
        } else {//查看全部单据时
            if ($view_rule == 2 && !$isSuperManager) {
                $canView_ids = array_merge($mine_ids, $canCheck_ids);
            } elseif ($view_rule == 3 && !$isSuperManager) {
                $canView_ids = array_merge($mine_ids, $canCheck_ids, $participant_ids);
            } else {
                return true;
            }
        }
        return array_unique($canView_ids);
    }


    private function getEbillCopyId($bill, $bill_id)
    {
        $ebill_copy = (new EbillCopy())->where(['bill' => $bill, 'bill_id' => $bill_id])->find();
        if ($ebill_copy) {
            $ebill_copy = $ebill_copy->toArray();
            return $ebill_copy['id'];
        }
        return null;
    }

    //-3=无权限发起签章，-2=无电子表单，-1=待发起，0=已发起待签章，1=已结束
    protected function getSignatureInfo($list)
    {
        $signatureModel = new Signature();
        foreach ($list->items() as &$item) {
            $bill = Config::get('database')['prefix'] . $this->model->getName();
            $bill_id = $item['id'];
            $ebill_id = $this->getEbillCopyId($bill, $bill_id);
            if ($ebill_id) {
                $signature = $signatureModel->where(['bill' => $bill, 'bill_id' => $bill_id])->order('id', 'desc')->select();
                if (count($signature) != 0) {
                    $item['fastflow_signature_status'] = (int)$signature[0]['status'];
                } else {
                    if ($item['initiator_id'] == $this->auth->getUserInfo()['id']) {
                        $item['fastflow_signature_status'] = -1;
                    } else {
                        $item['fastflow_signature_status'] = -3;
                    }
                }
            } else {
                $item['fastflow_signature_status'] = -2;
            }
        }
        return $list;
    }

}